package com.ruoyi.project.tool.swagger;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.demo.arrange.domain.CourseArrange;
import com.ruoyi.project.demo.arrange.service.ICourseArrangeService;
import com.ruoyi.project.demo.cart.domain.Cart;
import com.ruoyi.project.demo.cart.service.ICartService;
import com.ruoyi.project.demo.course.domain.Course;
import com.ruoyi.project.demo.course.service.ICourseService;
import com.ruoyi.project.demo.goods.domain.Goods;
import com.ruoyi.project.demo.goods.service.IGoodsService;
import com.ruoyi.project.demo.news.domain.News;
import com.ruoyi.project.demo.news.service.INewsService;
import com.ruoyi.project.demo.order.domain.CourseOrder;
import com.ruoyi.project.demo.order.service.ICourseOrderService;
import com.ruoyi.project.demo.question.domain.Question;
import com.ruoyi.project.demo.question.service.IQuestionService;
import com.ruoyi.project.demo.schedule.domain.Schedule;
import com.ruoyi.project.demo.schedule.service.IScheduleService;
import com.ruoyi.project.demo.type.domain.GoodType;
import com.ruoyi.project.demo.type.service.IGoodTypeService;
import com.ruoyi.project.system.role.domain.Role;
import com.ruoyi.project.system.role.service.IRoleService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

import io.swagger.annotations.Api;

@Api("APP接口")
@RestController
@RequestMapping("/api")
public class ApiController extends BaseController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IGoodTypeService goodTypeService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ICourseArrangeService arrangeService;
    @Autowired
    private ICourseService courseService;
    @Autowired
    private INewsService newsService;
    @Autowired
    private IScheduleService scheduleService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private ICartService cartService;
    @Autowired
    private ICourseOrderService courseOrderService;

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult loginApp(String username, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            User user = userService.selectUserById(getSysUser().getUserId());
            List<Role> roles = roleService.selectRolesByUserId(getSysUser().getUserId());
            if (roles != null && roles.size() > 0) {
                for (int i = 0; i < roles.size(); i++) {
                    if (roles.get(i).isFlag()) {
                        user.setRoleId(roles.get(i).getRoleId());
                        break;
                    }
                }
            }
            return success("登录成功", user);
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @PostMapping("/register")
    public AjaxResult registerApp(@RequestBody User user) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(userService.register(user));
    }

    @PostMapping("/editUser")
    public AjaxResult editUser(@RequestBody User user) {
        return toAjax(userService.updateUserInfo(user));
    }

    /**
     * 查询图书类型列表
     */
    @PostMapping("/getGoodTypes")
    @ResponseBody
    public AjaxResult getGoodTypes(GoodType goodType) {
        List<GoodType> list = goodTypeService.selectGoodTypeList(goodType);
        return success("查询成功", list);
    }

    /**
     * 查询我的购物车
     */
    @PostMapping("/getLikeList")
    @ResponseBody
    public AjaxResult getLikeList(Long usreId) {
        Cart cart = new Cart();
        cart.setUserId(usreId);
        List<Cart> list = cartService.selectCartList(cart);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setGoods(goodsService.selectGoodsById(list.get(i).getGid()));
        }
        return success("查询成功", list);
    }

    /**
     * 查询我的订单
     */
    @PostMapping("/getOrderList")
    @ResponseBody
    public AjaxResult getOrderList(CourseOrder order) {
        List<CourseOrder> list = courseOrderService.selectCourseOrderList(order);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setCourse(courseService.selectCourseById(list.get(i).getArrangeId()));
        }
        return success("查询成功", list);
    }

    /**
     * 查询知识
     */
    @PostMapping("/getCourseList")
    @ResponseBody
    public AjaxResult getCourseList(Course course) {
        List<Course> list = courseService.selectCourseList(course);
        return success("查询成功", list);
    }

    /**
     * 查询咨询
     */
    @PostMapping("/getNews")
    @ResponseBody
    public AjaxResult getNews(News news) {
        List<News> list = newsService.selectNewsList(news);
        return success("查询成功", list);
    }

    /**
     * 查询预约
     */
    @PostMapping("/getSchedule")
    @ResponseBody
    public AjaxResult getSchedule(Schedule schedule) {
        List<Schedule> list = scheduleService.selectScheduleList(schedule);
        return success("查询成功", list);
    }
    /**
     * 查询定制计划
     */
    @PostMapping("/getQuestion")
    @ResponseBody
    public AjaxResult getQuestion(Question question) {
        List<Question> list = questionService.selectQuestionList(question);
        return success("查询成功", list);
    }

    /**
     * 添加预约
     */
    @PostMapping("/addSchedule")
    public AjaxResult addSchedule(@RequestBody Schedule schedule) {
        scheduleService.insertSchedule(schedule);
        return success("添加成功");
    }

    /**
     * 编辑预约
     */
    @PostMapping("/editSchedule")

    public AjaxResult editSchedule(@RequestBody Schedule schedule) {
        scheduleService.updateSchedule(schedule);
        return success("编辑成功");
    }

    /**
     * 删除定制计划
     */
    @PostMapping("/delSchedule")
    @ResponseBody
    public AjaxResult delSchedule(Long id) {
        scheduleService.deleteScheduleById(id);
        return success("编辑成功");
    }

    /**
     * 查询知识安排
     */
    @PostMapping("/getCourseArrangeList")
    @ResponseBody
    public AjaxResult getCourseArrangeList(CourseArrange courseArrange) {
        CourseOrder order = new CourseOrder();
        order.setUserId(courseArrange.getUserId());
        List<CourseOrder> orders = courseOrderService.selectCourseOrderList(order);
        List<CourseArrange> arranges = new ArrayList<>();
        if (orders != null && orders.size() > 0) {
            for (int i = 0; i < orders.size(); i++) {
                courseArrange.setCourseId(orders.get(i).getArrangeId());
                arranges.addAll(arrangeService.selectCourseArrangeList(courseArrange));
            }
        }

        return success("查询成功", arranges);
    }

    /**
     * 查询知识
     */
    @PostMapping("/getDetail")
    @ResponseBody
    public AjaxResult getDetail(Long id) {
        Course course = courseService.selectCourseById(id);
        //查询当前已预约人数
        CourseArrange arrange = new CourseArrange();
        arrange.setCourseId(id);
        List<CourseArrange> arranges = arrangeService.selectCourseArrangeList(arrange);
        course.setArrangeList(arranges);
        return success("查询成功", course);
    }

    /**
     * 查询知识
     */
    @PostMapping("/getCouresArrangeDetail")
    @ResponseBody
    public AjaxResult getCouresArrangeDetail(Long id) {
        CourseArrange arrange = arrangeService.selectCourseArrangeById(id);
        arrange.setCourse(courseService.selectCourseById(arrange.getCourseId()));
        return success("查询成功", arrange);
    }

    /**
     * 购买知识
     */
    @PostMapping("/orderCourse")
    public AjaxResult orderBook(@RequestBody CourseOrder order) {
        //判断当前是否已经预定，如果预定则不能重复预定
        List<CourseOrder> orders = courseOrderService.selectCourseOrderList(order);
        if (orders != null && orders.size() > 0) {
            return error("已经预定过");
        }
        Course course = courseService.selectCourseById(order.getArrangeId());
        course.setCurNum(course.getCurNum() + 1);
        courseService.updateCourse(course);
        return toAjax(courseOrderService.insertCourseOrder(order));
    }

    /**
     * 更新上个次数
     */
    @PostMapping("/orderCourseNum")
    public AjaxResult orderCourseNum(@RequestBody CourseOrder order) {
        //判断当前是否已经预定，如果预定则不能重复预定
        List<CourseOrder> orders = courseOrderService.selectCourseOrderList(order);
        if (orders.size() > 0) {
            if (orders.get(0).getNum() == 0) {
                //不需要验证码
                orders.get(0).setNum(orders.get(0).getNum() + 1);
                courseOrderService.updateCourseOrder(orders.get(0));
            } else {//验证验证码
                if (order.getCode().equals("8888")) {
                    orders.get(0).setNum(orders.get(0).getNum() + 1);
                    courseOrderService.updateCourseOrder(orders.get(0));
                } else {
                    error("验证码错误！请联系教练");
                }

            }
        }

        return toAjax(courseOrderService.insertCourseOrder(order));
    }

    /**
     * 加入购物车
     */
    @PostMapping("/addToCart")
    @ResponseBody
    public AjaxResult addToCart(@RequestBody Cart cart) {
        return toAjax(cartService.insertCart(cart));
    }
}
